//
//  BaseVC.swift
//  GameDemo
//
//  Created by woniu on 2025/8/15.
//

import Foundation
import UIKit
import SnapKit

class BaseVC: UIViewController {
    public var backButton:UIButton!
    public var drawingBoardView:DrawingBoardView!
    public var drawingButton:UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .black
        self.navigationController?.navigationBar.isHidden = true
        self.navigationController?.isNavigationBarHidden = true
        createUI()
    }
    
    private func createUI(){
        backButton = UIButton(type: .custom)
        backButton.backgroundColor = .black
        backButton.setImage(UIImage(named: "返回"), for: .normal)
        backButton.imageView?.contentMode = .scaleAspectFit
        backButton.addTarget(self, action: #selector(onBack), for: .touchUpInside)
        self.view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(5)
            make.top.equalToSuperview().offset(25)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        //画笔
        drawingButton = UIButton(type: .system)
        drawingButton.setImage(UIImage(named: "画笔_白色"), for: .normal)
        drawingButton.tintColor = .white
        drawingButton.addTarget(self, action: #selector(onShowOrHiddenDraw), for: .touchUpInside)
        
        //画板
        drawingBoardView = DrawingBoardView(frame: .zero)
        drawingBoardView.isHidden = true
        drawingBoardView.onCancelBlock = {[weak self]in
            self?.dismisDrawingBoard()
        }
       
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //添加到最顶层
        if drawingButton.superview == nil{
            self.view.addSubview(drawingButton)
            drawingButton.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 40, height: 40))
                make.centerX.equalToSuperview().offset(50)
                make.centerY.equalTo(backButton.snp.centerY)
            }
        }
    }
    
    @objc func onShowOrHiddenDraw(){
        if drawingBoardView.isHidden{
            showDrawingBoard()
        }else{
            dismisDrawingBoard()
        }
    }
    
    private func showDrawingBoard(){
        drawingBoardView.isHidden = false
        self.view.addSubview(drawingBoardView)
        drawingBoardView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func dismisDrawingBoard(){
        drawingBoardView.removeFromSuperview()
        drawingBoardView.isHidden = true
    }
    
    @objc func onBack(){
        // self.dismiss(animated: true)
         guard let _ = self.navigationController?.popViewController(animated: true) else {
            self.dismiss(animated: true)
            return
        } 
    }
}
